import datetime
from typing import List

from fastapi import APIRouter, Depends, Query, Request, Path
from pydantic import BaseModel, Field
from sqlalchemy import literal_column, text
from sqlalchemy.orm import Session
from commons.BaseResponse import BaseResponse
from datebase import get_db
from models.sysModel.mylab import AmSysUser, ATsSite, AmSysUserRole, AmSysRolePermission, AmSysPermission, AmSysRole
from utils.EncryptionUtil import TokenVerify, EncryptionMiddleware, oauth2_scheme, get_current_user

my_lab_router = APIRouter(tags=["登录接口"])


# 退出
@my_lab_router.post("/sys/auth/logout", summary="退出系统")
def logout():
    return BaseResponse.success()


class loginUser(BaseModel):
    username: int = Field(None, description="用户名|id")
    password: str = Field(None, description="密码")
    captcha: str = Field(default=None, description="验证码")


# 登录接口
@my_lab_router.post("/auth/user/login", response_model=BaseResponse, summary="id+密码登录")
def loginById(login: loginUser, db: Session = Depends(get_db), ):
    user = db.query(AmSysUser).filter(AmSysUser.id == login.username).one()
    if user:
        # 验证密码
        if login.password == user.password_clear:
            # 生成token
            tokenVerify = TokenVerify(
                user_id=user.id,
                user_name=user.username
            )
            token = EncryptionMiddleware.encrypt_token(tokenVerify)
            user_info = (db.query(AmSysUser)
                         .join(ATsSite, AmSysUser.fsite_no_belong == ATsSite.fsite_no)
                         .filter(AmSysUser.id == login.username)).all()
            if not user_info:
                return BaseResponse.error(message="客户信息不存在")
            # for item in user_info:
            data = {"tokenHead": "Bearer ", "token": token, "user": login,
                    "bigScreenUrl": u"http://139.224.13.75:18080/"}
            return BaseResponse.success(data=data)
    return BaseResponse.error(message="账号密码有误")


@my_lab_router.get("/sys/auth/info", summary="获取权限信息")
def sys_info(db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)):
    # user_id = get_current_user(token)
    # print(user_id)
    # 解密字符串
    if token is None:
        return BaseResponse.error(message="未获得授权")
    tokenVerify = EncryptionMiddleware.decrypt_token(token)
    user_id = tokenVerify["user_id"]
    # 查询用户角色（只返回角色 ID）
    roles = db.query(AmSysUserRole.role_id).filter(AmSysUserRole.user_id == user_id).all()
    my_role = [row[0] for row in roles]  # 直接提取 ID 值

    # 查询用户权限（只返回权限值）
    user_menus = (
        db.query(AmSysPermission.value)
        .join(AmSysRolePermission, AmSysRolePermission.permission_id == AmSysPermission.id)
        .join(AmSysRole, AmSysRolePermission.role_id == AmSysRole.id)
        .join(AmSysUserRole, AmSysRole.id == AmSysUserRole.role_id)
        .filter(AmSysUserRole.user_id == user_id)
        .order_by(AmSysPermission.id)
        .all()
    )
    my_menu = [row[0] for row in user_menus]  # 提取权限值

    # 查询用户信息（使用 _asdict() 转换 Row 对象）
    user_data = (
        db.query(
            AmSysUser.id,
            AmSysUser.username,
            AmSysUser.fsite_no_belong,
            ATsSite.fsite_name,
            ATsSite.fsite_level,
            literal_column("'003'").label("tenantNo"),
            literal_column("null").label("avatar")
        )
        .outerjoin(ATsSite, AmSysUser.fsite_no_belong == ATsSite.fsite_no)
        .filter(AmSysUser.id == user_id)
        .first()
    )

    if not user_data:
        return BaseResponse.error(message="用户不存在")

    # 将 Row 对象转为字典
    user_data_dict = user_data._asdict()

    # 构建响应数据
    data_result = {
        "id": user_id,
        "name": user_data_dict["username"],
        "fsiteNo": user_data_dict["fsite_no_belong"],
        "fsiteName": user_data_dict["fsite_name"] or "",
        "fsiteLevel": user_data_dict["fsite_level"] or "",
        "tenantNo": user_data_dict["tenantNo"],
        "bigScreenUrl": "http://139.224.13.75:18080/",
        "avatar": user_data_dict["avatar"],
        "roles": my_role,
        "perms": my_menu,
    }

    return BaseResponse.success(data=data_result)


# 获取用户目录
@my_lab_router.get("/screen/getDynamicMenu", summary="获取目录信息")
def get_dynamic_menu(db: Session = Depends(get_db), token: str = Query(), systype: str = Query(default="S")):
    if token is None:
        return BaseResponse.error(message="未授权")
    # 获取用户id
    token = token[7:]
    tokenVerify = EncryptionMiddleware.decrypt_token(token)
    user_id = tokenVerify["user_id"]

    # 获取菜单
    menu_data = (db.query(AmSysPermission.id, AmSysPermission.pid, AmSysPermission.name,
                          AmSysPermission.value.label("compent"), AmSysPermission.uri.label("path"),
                          AmSysPermission.fname, AmSysPermission.yname)
                 .join(AmSysRolePermission, AmSysRolePermission.permission_id == AmSysPermission.id)
                 .join(AmSysUserRole, AmSysUserRole.role_id == AmSysRolePermission.role_id)
                 .filter(AmSysUserRole.user_id == user_id)
                 .filter(AmSysPermission.systype == systype)
                 .order_by(AmSysPermission.pid, AmSysPermission.sort_seq, AmSysPermission.id)
                 .all())

    menu_data2 = menu_data
    menu_data3 = menu_data

    # 逐层遍历
    mydata = []
    for key in range(len(menu_data)):
        if (str(menu_data[key][1]) == '0'):
            menuid = menu_data[key][0]
            strpath = menu_data[key][4]
            d1 = {}
            d1['path'] = strpath
            try:
                d1['name'] = strpath.replace('/', '')
            except Exception as e:
                # print(e)
                continue
            d1['fname'] = None
            d1['yname'] = None
            d1['component'] = None
            d1['alwaysShow'] = True
            d1['redirect'] = "noredirect"
            # meta
            d_meta = {}
            d_meta['title'] = menu_data[key][2]
            d_meta['ftitle'] = None
            d_meta['ytitle'] = None
            d_meta['keepAlive'] = True  # False
            d_meta['noCache'] = True
            d1['meta'] = d_meta

            # 第2层菜单
            d2_list = []
            for key2 in range(len(menu_data2)):
                if (str(menu_data2[key2][1]) == str(menuid)):
                    menuid2 = menu_data2[key2][0]
                    strpath = menu_data2[key2][4]
                    d2 = {}
                    d2['path'] = strpath
                    d2['name'] = strpath.replace('/', '')
                    d2['component'] = menu_data2[key2][3]
                    d2['alwaysShow'] = True
                    d2['redirect'] = "noredirect"
                    d2['fname'] = None
                    d2['yname'] = None
                    # meta
                    d_meta2 = {}
                    d_meta2['title'] = menu_data2[key2][2]
                    d_meta2['ftitle'] = None
                    d_meta2['ytitle'] = None
                    d_meta2['keepAlive'] = True  # False
                    d_meta2['noCache'] = True
                    d2['meta'] = d_meta2

                    # 第3层菜单
                    i = 0
                    d3_list = []
                    for key3 in range(len(menu_data3)):
                        if (str(menu_data3[key3][1]) == str(menuid2)):
                            i = i + 1
                            strpath = menu_data3[key3][4]
                            d3 = {}
                            d3['path'] = strpath
                            d3['name'] = strpath.replace('/', '')
                            d3['component'] = menu_data3[key3][3]
                            d3['redirect'] = None
                            d3['fname'] = None
                            d3['yname'] = None
                            d3['children'] = None
                            d3['alwaysShow'] = False
                            # meta
                            d_meta3 = {}
                            d_meta3['title'] = menu_data3[key3][2]
                            d_meta3['ftitle'] = None
                            d_meta3['ytitle'] = None
                            d_meta3['keepAlive'] = True  # False
                            d_meta3['noCache'] = True
                            d3['meta'] = d_meta3

                            d3_list.append(d3)

                    if (i > 0):
                        d2['redirect'] = "noredirect"
                        d2['children'] = d3_list
                    else:
                        d2['redirect'] = None
                        d2['children'] = None

                    d2_list.append(d2)
                    # children
                    d1['children'] = d2_list

            # 加入
            mydata.append(d1)

    # 将json格式字符串输出原有顺序
    data = {"list": mydata}

    return BaseResponse.success(data=data)


@my_lab_router.get("/screen/getDynamicMenuByUserid", summary="使用用户id获取目录信息")
def get_dynamic_menu_by_userid(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
    try:
        if token is None:
            return BaseResponse.error(message="未授权")
        # 获取用户id
        token = token[7:]
        tokenVerify = EncryptionMiddleware.decrypt_token(token)
        user_id = tokenVerify["user_id"]

        sql = "select b.id,b.pid,b.name,b.value component,b.uri path,b.fname,b.yname"
        sql = sql + " from am_sys_role_permission a,am_sys_permission b,am_sys_user_role s"
        sql = sql + " where s.user_id=" + user_id
        sql = sql + " and a.role_id=s.role_id"
        sql = sql + " and a.permission_id=b.id"
        sql = sql + " order by b.pid,b.sort_seq,b.id"

        menu_data = db.execute(text(sql)).fetchall()

        # 第2层菜单
        menu_data2 = menu_data
        # 第3层菜单
        menu_data3 = menu_data

        # 逐层遍历
        mydata = []
        for key in range(len(menu_data)):
            if (str(menu_data[key][1]) == '0'):
                menuid = menu_data[key][0]
                d1 = {}
                d1['path'] = menu_data[key][4]
                d1['name'] = menu_data[key][2]
                d1['fname'] = None
                d1['yname'] = None
                d1['component'] = None
                d1['alwaysShow'] = True
                d1['redirect'] = "noredirect"
                # meta
                d_meta = {}
                d_meta['title'] = menu_data[key][2]
                d_meta['ftitle'] = None
                d_meta['ytitle'] = None
                d_meta['keepAlive'] = True  # False
                d_meta['noCache'] = True
                d1['meta'] = d_meta

                # 第2层菜单
                d2_list = []
                for key2 in range(len(menu_data2)):
                    if (str(menu_data2[key2][1]) == str(menuid)):
                        menuid2 = menu_data2[key2][0]
                        d2 = {}
                        d2['path'] = menu_data2[key2][4]
                        d2['name'] = menu_data2[key2][2]
                        d2['component'] = menu_data2[key2][3]
                        d2['alwaysShow'] = True

                        d2['fname'] = None
                        d2['yname'] = None
                        # meta
                        d_meta2 = {}
                        d_meta2['title'] = menu_data2[key2][2]
                        d_meta2['ftitle'] = None
                        d_meta2['ytitle'] = None
                        d_meta2['keepAlive'] = True  # False
                        d_meta2['noCache'] = True
                        d2['meta'] = d_meta2

                        # 第3层菜单
                        i = 0
                        d3_list = []
                        for key3 in range(len(menu_data3)):
                            if (str(menu_data3[key3][1]) == str(menuid2)):
                                i = i + 1
                                d3 = {}
                                d3['path'] = menu_data3[key3][4]
                                d3['name'] = menu_data3[key3][2]
                                d3['component'] = menu_data3[key3][3]
                                d3['redirect'] = None
                                d3['fname'] = None
                                d3['yname'] = None
                                d3['children'] = None
                                d3['alwaysShow'] = False
                                # meta
                                d_meta3 = {}
                                d_meta3['title'] = menu_data3[key2][2]
                                d_meta3['ftitle'] = None
                                d_meta3['ytitle'] = None
                                d_meta3['keepAlive'] = True  # False
                                d_meta3['noCache'] = True
                                d3['meta'] = d_meta3

                                d3_list.append(d3)

                        if (i > 0):
                            d2['redirect'] = "noredirect"
                            d2['children'] = d3_list
                        else:
                            d2['redirect'] = None
                            d2['children'] = None

                        d2_list.append(d2)
                        # children
                        d1['children'] = d2_list

                # 加入
                mydata.append(d1)

        # 将json格式字符串输出原有顺序
        data = {"list": mydata}
        # print(data)
        return BaseResponse.success(data=data)
    except Exception as e:
        return BaseResponse.error(message=str(e))


@my_lab_router.get("/screen/permissions/{id}", summary="角色授权列表")
def get_screen_permission(id: int, token: str = Depends(oauth2_scheme), db: Session = Depends(get_db),
                          systype: str = Query(default="S")):
    # 当前菜单
    sql = "select id,pid,name from am_sys_permission where status=1 "
    sql = sql + " and systype = :systype"
    sql = sql + " order by pid,sort_seq"
    menu_data = db.execute(text(sql), {"systype": systype}).fetchall()

    # 第2层菜单
    menu_data2 = menu_data
    # 第3层菜单
    menu_data3 = menu_data

    # 逐层遍历
    mydata = []
    for key in range(len(menu_data)):
        if (str(menu_data[key][1]) == '0'):
            menuid = menu_data[key][0]
            d1 = {}
            d1['id'] = menu_data[key][0]
            d1['label'] = menu_data[key][2]

            # 第2层菜单
            d2_list = []
            for key2 in range(len(menu_data2)):
                if (str(menu_data2[key2][1]) == str(menuid)):
                    menuid2 = menu_data2[key2][0]
                    d2 = {}
                    d2['id'] = menu_data2[key2][0]
                    d2['label'] = menu_data2[key2][2]

                    # 第3层菜单
                    d3_list = []
                    for key3 in range(len(menu_data3)):
                        if (str(menu_data3[key3][1]) == str(menuid2)):
                            d3 = {}
                            d3['id'] = menu_data3[key3][0]
                            d3['label'] = menu_data3[key3][2]
                            d3_list.append(d3)
                    d2['children'] = d3_list
                    d2_list.append(d2)
                    # children
                    d1['children'] = d2_list

            # 加入
            mydata.append(d1)

    # 角色权限
    sql = "select asrp.permission_id permission_id"
    sql = sql + " from am_sys_role_permission asrp"
    sql = sql + " left join am_sys_permission asp"
    sql = sql + " on asrp.permission_id = asp.id"
    sql = sql + " where asrp.role_id=:id and asp.systype = :systype"
    # sql = "select permission_id"
    # sql = sql + " from am_sys_role_permission "
    # sql = sql + " where role_id=" + str(id)
    # sql = sql + " and systype = '"+systype+"'"
    rolemenu = db.execute(text(sql), {"id": id, "systype": systype}).fetchall()
    assigned = []
    for key in range(len(rolemenu)):
        assigned.append(rolemenu[key][0])

    # 将json格式字符串输出原有顺序
    data = {"all": mydata, "assigned": assigned}
    return BaseResponse.success(data=data)


@my_lab_router.get("/auth/user/resetpassword/{id}", summary="用户密码重置")
def resect_password(id: int, db: Session = Depends(get_db)):
    sql = "update am_sys_user set password_clear='123456' where id= :id"

    i = db.execute(text(sql), {"id": id}).fetchall()

    if i != None:
        return BaseResponse.success()
    else:
        return BaseResponse.error()


class UpLoadData(BaseModel):
    absorbance: int
    cardinalNumberUnit: str
    clientCompany: str
    clientPeople: str
    clientPhone: str
    detectionCompany: str
    detectionDate: datetime.datetime
    detectionMethod: str
    detectionPeople: str
    detectionPhone: str
    detectionResult: int
    detectionResultText: str
    detectionValue: str
    deviceCode: str
    deviceType: int
    inhibitionRatio: str
    locationDetection: str
    locationRecheck: str
    locationSampling: str
    phoneNumber: str
    projectType: int
    randomId: str
    recheckCompany: str
    recheckPeople: str
    recheckPhone: str
    sampleBatch: str
    sampleName: str
    sampleNumber: str
    sampleSource: str
    samplingCardinalNumber: str
    samplingCompany: str
    samplingPeople: str
    samplingPhone: str
    testProject: str
    unit: str


@my_lab_router.post("/upload/addList10", summary="测试接送数据上传")
def json_test(json_data: List[UpLoadData], request: Request, db: Session = Depends(get_db)):
    sql = "insert into public.a_a_json_test values (1,:json,'测试')"

    for data in json_data:
        print(data.dict())
        # i = db.execute(text(sql), {"json": data.dict()}).scalar()

    print([data.dict() for data in json_data])

    return BaseResponse.success()


@my_lab_router.get("/getRolePermission/{userid}", summary="根据用户id获取权限信息")
def get_role_permission(userid: int = Path(description="用户id"), db: Session = Depends(get_db)):
    sql = " select asrp.* from am_sys_user asu "
    sql = sql + " left join am_sys_user_role asur on asu.id = asur.user_id "
    sql = sql + " left join am_sys_role_permission asrp on asur.role_id = asrp.role_id "
    sql = sql + " where asu.id= :userid "
    data = db.execute(text(sql), {"userid": userid}).fetchall()
    list = []
    for key in range(len(data)):
        d1 = {}
        d1['id'] = data[key][0]
        d1["roleId"] = data[key][1]
        d1["permissionId"] = data[key][2]
        list.append(d1)
    result = {"list": list}
    return BaseResponse.success(data=result)
